import React from 'react'
import { connect } from 'dva'
import queryString from 'query-string'
import {
  Card,
  Badge,
  Table,
  Divider,
  Row,
  Col,
  Button,
  Modal
} from 'antd'
import DescriptionList from 'components/DescriptionList'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import FooterToolbar from 'components/FooterToolbar'
import styles from './index.less'
import { financialSettlementStatus, financialBusinessType } from 'utils/enumConfig'

const doSettlementApplies4Receivable = ({location, dispatch, doSettlement4Receivable, loading}) => {
  const {Description} = DescriptionList
  const {
    items,
    pagination,
    settlementApplies,
    receiptBills,
    selectedReceiptBills,
    selectedRowKeys
  } = doSettlement4Receivable

  // 处理PageHeaderLayout
  const breadcrumbList = [
    {
      title: '财务管理',
      href: '/financialSettlementApply'
    }, {
      title: '财务结算',
      href: '/financialSettlementApply'
    }, {
      title: '抵扣收款单'
    }
  ]
  const pageProps = {
    breadcrumbList: breadcrumbList,
    title: '抵扣收款单',
    content: '请先选择已抵扣且有余额的收款单'
  }

  // 处理结算金额信息
  const settlementMoneyColumns = [
    {
      title: '单据编号',
      dataIndex: 'orderId',
      key: 'orderId',
      render: (text, record, index) => (record.orderId)
    }, {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      render: (text, record, index) => (financialBusinessType[record.businessType])
    }, {
      title: '应收金额',
      dataIndex: 'amountReceivable',
      key: 'amountReceivable',
      render: (text, record, index) => (record.settlementType === 'RECEIVABLE'
        ? record.settlementMoney.toFixed(2)
        : '——')
    }, {
      title: '应付金额',
      dataIndex: 'amountPayable',
      key: 'amountPayable',
      render: (text, record, index) => (record.settlementType === 'PAYABLE'
        ? record.settlementMoney.toFixed(2)
        : '——')
    }
  ]

  // 收款单信息
  const receiptBillsColumns = [
    {
      title: '收款单号',
      dataIndex: 'receiptBillNum',
      key: 'receiptBillNum',
      render: (text, record, index) => (record.num)
    }, {
      title: '收款金额',
      dataIndex: 'received',
      key: 'received',
      render: (text, record, index) => (record.received)
    }, {
      title: '已抵扣金额',
      dataIndex: 'amountReceivable',
      key: 'amountReceivable',
      render: (text, record, index) => (record.received - record.availableBalance)
    }, {
      title: '余额',
      dataIndex: 'availableBalance',
      key: 'availableBalance',
      render: (text, record, index) => (record.availableBalance)
    }, {
      title: '备注',
      dataIndex: 'memo',
      key: 'memo',
      render: (text, record, index) => (record.memo)
    }
  ]

  // 处理商家用户信息
  let financialAccountName = ''
  let creatorName = ''
  if (settlementApplies && settlementApplies.length > 0) {
    financialAccountName = settlementApplies[0].financialAccountName
    creatorName = settlementApplies[0].creatorName
  }

  // 处理金额信息
  let amountReceivable = 0
  let amountPayable = 0
  let totalAmount = 0
  if (settlementApplies && settlementApplies.length > 0) {
    // 计算总的应收金额
    let receivableApply = settlementApplies.filter((apply) => {
      return apply.settlementType === 'RECEIVABLE'
    })
    _.each(receivableApply, (apply) => {
      amountReceivable += apply.settlementMoney
    })
    // 计算总的应付金额
    let payableApply = settlementApplies.filter((apply) => {
      return apply.settlementType === 'PAYABLE'
    })
    _.each(payableApply, (apply) => {
      amountPayable += apply.settlementMoney
    })
    // 计算总金额
    totalAmount = Math.abs(amountReceivable - amountPayable)
  }

  /**
   * 当选择收款单进行冲抵时的逻辑处理
   * @param {*} record
   * @param {*} selected
   * @param {*} selectedRows
   * @param {*} nativeEvent
   */
  const onSelectRows = (record, selected, selectedRows, nativeEvent) => {
    // selected = false;
    if (selected || selectedRows.length > 0) {
      // 1. 请先抵抗已经抵扣过的收款单
      let offsetReceiptBill = _.find(receiptBills, (receiptBill) => {
        return receiptBill.received != receiptBill.availableBalance
      })
      let selectedRowKeys = selectedRows.map((row) => {
        return row.id
      })
      if (offsetReceiptBill && _.indexOf(selectedRowKeys, offsetReceiptBill.id) < 0) {
        Modal.info({title: '提示', content: `编号为${offsetReceiptBill.num}的付款单已被抵扣过，请优先使用该付款单进行抵扣`})
        dispatch({
          type: 'doSettlement4Receivable/updateState',
          payload: {
            selectedRowKeys: []
          }
        })
        return
      }
      // 2. 当第一个收款单已足够冲抵，无法再选中第二个收款单。
      if (selectedRows.length > 1) {
        const lastSelectedRows = selectedRows.pop()
        let existingBalance = 0
        _.each(selectedRows, (row) => {
          existingBalance += row.availableBalance
        })
        if (existingBalance >= totalAmount) {
          Modal.info({title: '提示', content: `之前选中的收款单余额已足够，不需要继续冲抵`})
          let selectedRowKeys = selectedRows.map((row) => {
            return row.id
          })
          dispatch({
            type: 'doSettlement4Receivable/updateState',
            payload: {
              selectedRowKeys: selectedRowKeys
            }
          })
        }
      }
    } else {
      Modal.info({title: '提示', content: `请至少选中一个进行抵扣`})
      return
    }
  }

  // 设置默认选中值
  const onChange = (selectedRowKeys) => {
    dispatch({
      type: 'doSettlement4Receivable/updateState',
      payload: {
        selectedRowKeys: selectedRowKeys
      }
    })
  }

  const rowSelection = {
    type: 'check',
    selectedRowKeys: selectedRowKeys,
    onChange: onChange,
    onSelect: onSelectRows
  }

  /** 当选择收款单进行冲抵时的逻辑处理-end */

  /**
   * 进行结算
   */
  const submitSettlementScheme = (selectedRowKeys) => {
    if (selectedRowKeys === undefined || selectedRowKeys === null || selectedRowKeys.length <= 0) {
      Modal.info({title: '提示', content: `请至少选中一个进行抵扣`})
      return
    }
    const applyIds = settlementApplies.map((apply) => {
      return apply.id
    })
    dispatch({
      type: 'doSettlement4Receivable/receivable',
      payload: {
        applyIds: applyIds,
        receiptIds: selectedRowKeys
      }
    })
  }

  return (
    <PageHeaderLayout {...pageProps}>
      <Card className={styles.card} bordered={false}>
        <DescriptionList
          size="large"
          title="基础信息"
          style={{
            marginBottom: 32
          }}>
          <Description term="商家">{financialAccountName}</Description>
          <Description term="联系人">{creatorName}</Description>
          <Description term="结算类型">应收</Description>
          <Description term="应收金额">{'¥ ' + amountReceivable.toFixed(2)}</Description>
          <Description term="应付金额">{'¥ ' + amountPayable.toFixed(2)}</Description>
          <Description term="总计">
            {'¥ ' + totalAmount.toFixed(2)}<span>（应收）</span>
          </Description>
        </DescriptionList>
        <Divider style={{
          marginBottom: 32
        }}/>
        <div className={styles.title}>待结算申请单</div>
        <Table
          style={{
            marginBottom: 24
          }}
          pagination={false}
          bordered
          dataSource={settlementApplies}
          columns={settlementMoneyColumns}
          rowKey="id"/>
        <Divider style={{
          marginBottom: 32
        }}/>
        <div className={styles.title}>可抵扣收款单</div>
        <Table
          style={{
            marginBottom: 24
          }}
          pagination={false}
          rowSelection={rowSelection}
          bordered
          dataSource={receiptBills}
          columns={receiptBillsColumns}
          rowKey="id"/>
        <FooterToolbar style={{
          width: '100%'
        }}>
          <Button type="primary" onClick={() => submitSettlementScheme(selectedRowKeys)}>
            提交
          </Button>
        </FooterToolbar>
      </Card>
    </PageHeaderLayout>
  )
}

export default connect(({doSettlement4Receivable, loading}) => ({
  doSettlement4Receivable,
  loading
}))(doSettlementApplies4Receivable)
